﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using GiaoTrinhEPU.Repositories;

namespace GiaoTrinhEPU.Helpers.ManagerMenuBuilder
{
    public static class HtmlHelperManagerMenu
    {
        public static MvcHtmlString ManagerMenuAsUnorderedList(this HtmlHelper helper, List<Menu> managerLinks, int selectedId, bool enabled = true)
        {
            if (managerLinks == null || managerLinks.Count == 0)
                return MvcHtmlString.Empty;
            var topLevelParentId = ManagerLinkListHelper.GetTopLevelParentId(managerLinks);

            return MvcHtmlString.Create(BuildMenuItems(managerLinks, topLevelParentId, 0, selectedId, enabled));
        }

        private static string BuildMenuItems(List<Menu> managerLinks, int parentId, int level, int selectedId, bool enabled = true)
        {
            var oldLevel = level;
            var parentTag = new TagBuilder("ul");

            var childManagerLinks = ManagerLinkListHelper.GetChildManagerLinks(managerLinks, parentId);

            foreach (var managerLink in childManagerLinks)
            {
                level++;

                var itemTag = new TagBuilder("li");
                if (selectedId == managerLink.Id)
                {
                    itemTag.AddCssClass("selected");
                }
                if (enabled == false)
                {
                    itemTag.AddCssClass("disable");
                }

                var anchorTag = new TagBuilder("a");
                if (enabled == true)
                {
                    anchorTag.MergeAttribute("href", managerLink.Link);
                }
                anchorTag.SetInnerText(managerLink.Name);
                if (managerLink.Target != null)
                {
                    anchorTag.MergeAttribute("target", managerLink.Target);
                }

                Boolean managerLinkHasChildren = ManagerLinkListHelper.ManagerLinkHasChildren(managerLinks, managerLink.Id);

                if (managerLinkHasChildren && level > 1)
                {
                    anchorTag.AddCssClass("parent");
                }
                itemTag.InnerHtml = anchorTag.ToString();

                if (managerLinkHasChildren && enabled == true)
                {
                    itemTag.InnerHtml += BuildMenuItems(managerLinks, managerLink.Id, level, selectedId);
                }
                parentTag.InnerHtml += itemTag;
                level = oldLevel;
            }
            return parentTag.ToString();
        }
    }
}
